package com.njrsrc.android.tasks;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.common.utils.Helpers;
import com.njrsrc.common.utils.MsgID;

public class CensusQueryTask extends AsyncTask<Object, Integer, Void> {
	private String url;
	private Handler mHandler;
	private UserInfo userInfo;
	private List<UserInfo> archivesList;

	@Override
	protected Void doInBackground(Object... params) {
		if (params.length < 4) {
			return null;
		}
		mHandler = (Handler) params[0];
		url = (String) params[1];
		userInfo = (UserInfo) params[2];
		archivesList = (List<UserInfo>) params[3];
		JSONObject jsonObject = Helpers.getJSONArrayByGet(url);
		Message msg = mHandler.obtainMessage();
		try {
			if (jsonObject == null) {
				msg.what = MsgID.ARCHIVES_QUERY_ERROR;
			} else if (jsonObject.toString().contains("error_code")) {
				// 返回错误
				userInfo.setError_code(jsonObject.getString("error_code"));
				userInfo.setError_message(jsonObject.getString("error_message"));
				msg.what = MsgID.ARCHIVES_QUERY_FAIL;
			} else {
				msg.what = MsgID.ARCHIVES_QUERY_SUCCESS;
				JSONArray archivesArray = jsonObject.getJSONArray("archives");
				for (int i = 0; i < archivesArray.length(); i++) {
					userInfo = new UserInfo();
					userInfo.setDang_an_id(((JSONObject) archivesArray.opt(i)).getString("dang_an_id"));
					userInfo.setName(((JSONObject) archivesArray.opt(i)).getString("name"));
					userInfo.setSex(((JSONObject) archivesArray.opt(i)).getString("sex"));
					userInfo.setBirthday(((JSONObject) archivesArray.opt(i)).getString("birthday"));
					userInfo.setStatus(((JSONObject) archivesArray.opt(i)).getString("status"));
					archivesList.add(userInfo);
					userInfo = null;
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mHandler.sendMessage(msg);
		return null;
	}
}